/**
 * File:   ComplexCleaner.java
 * Author: Gvennet
 */
package dht.cleaners;

import dht.identifier.identifier.Identifier;
import dht.node.DHTNodeContacts;
import dht.node.DHTNodeModel;
import dht.node.DHTNodeRow;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * todo write javadoc
 */
public final class ComplexCleaner implements NodeModelCleaner, Runnable
{

	private DHTNodeModel nodeModel;

	private final Identifier identifier;

	public ComplexCleaner(Identifier identifier)
	{
		this.identifier = identifier;
	}

	//@Override

	public void clean()
	{
		if (nodeModel != null)
		{
			List<DHTNodeRow> nodes = nodeModel.getNodes();
			if (nodes.size() == nodeModel.getMaxSize())
			{
				Identifier[] identifiers = new Identifier[nodes.size()];
				for (int i = 0; i < nodes.size(); i++)
				{
					identifiers[i] = nodes.get(i).getId();
				}

				Arrays.sort(identifiers, new Comparator<Identifier>()
				{

					//@Override
					public int compare(Identifier o, Identifier o1)
					{
						return o.getDistance(identifier).compareTo(o1.getDistance(identifier));
					}
				});

				for (DHTNodeRow node : nodes)
				{

					for (int i = identifiers.length; i < identifiers.length / 2; i--)
					{

						if (node.getId().compareTo(identifiers[i]) == 0)
						{
							nodeModel.remove(new DHTNodeContacts(node.getInetAddress(), node.getPort()));
						}
					}
				}

			}
		}
	}

	//@Override

	public void setNodeModel(DHTNodeModel nodeModel)
	{
		this.nodeModel = nodeModel;
	}

	//@Override

	public void run()
	{
		clean();
	}
}
